import React, {useState} from 'react'
import {View, Image, Input, Textarea, Text, Button, Label, Picker} from '@tarojs/components'
import Nav from '@/components/Nav/Nav'
import Taro, {useReady, useRouter} from '@tarojs/taro'
import {addPicture, addStraight, uploadImage} from '@/packageC/api/upload'
import Loading, {useLoading} from '@/components/Loading/Loading'
import './Upload.scss'

interface UploadRet {
  status: string,
  value?: {
    data: {
      path: string,
      filename: string
    },
    [key: string]: any
  },
  reason?: string
}

const Upload: React.FC = () => {
  const [imgList, setImgList] = useState<string[]>([])
  const {show, showLoading, hideLoading} = useLoading()
  const {params} = useRouter<{type: string}>()

  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [area, setArea] = useState<string[]>(['重庆市', '重庆市', '合川区'])

  useReady(() => {
    let obj = Taro.getStorageSync('cacheUpdate')
    setTitle(obj.title)
    setArea(obj.area)
    setContent(obj.content)
    setImgList(obj.imgList)
  })

  function onchangeTitle (e) {
    setTitle(e.detail.value)
  }
  function onchangeContent (e) {
    setContent(e.detail.value)
  }

  function onChangeArea (e) {
    setArea(e.detail.value)
  }

  async function onSend () {
    if (!title) {
      Taro.showToast({
        title: '标题不能为空',
        icon: 'none'
      })
      return
    }
    if (!content) {
      Taro.showToast({
        title: '内容不能为空',
        icon: 'none'
      })
      return
    }
    if (imgList.length === 0) {
      Taro.showToast({
        title: '图片不能为空',
        icon: 'none'
      })
      return
    }
    let id: string
    if (params.type === 'recommend') {
      id = await addStraight(title, content, imgList[0])
    } else {
      id = await addPicture(title, content, imgList[0])
    }
    if (!id) {
      Taro.showToast({
        title: '发送错误，请稍后重试',
        icon: 'none'
      })
      return
    }
    setTitle('')
    setContent('')
    setArea(['重庆市', '重庆市', '合川区'])
    setImgList([])
    Taro.showToast({
      title: '上传成功'
    })
    setTimeout(() => {
      Taro.navigateBack({
        delta: 1
      })
    }, 1000)
  }

  function cacheData () {
    let obj = {
      title,
      content,
      area,
      imgList
    }
    Taro.setStorageSync('cacheUpdate', obj)
    Taro.showToast({
      title: '保存成功'
    })
  }

  async function selectImage (e) {
    e.stopPropagation()
    try {
      let res = await Taro.chooseImage({
        count: 3,
        sizeType: ['original'],
        sourceType: ['album', 'camera']
      })

      showLoading()

      let arr: Promise<any>[] = []
      let byte = 2500 * 1024
      for (let i = 0; i < res.tempFilePaths.length; i++) {
        if (!imgList.includes(res.tempFilePaths[i])) {
          if (byte < res.tempFiles[i].size) {
            await Taro.compressImage({
              src: res.tempFilePaths[i],
              quality: byte / res.tempFiles[i].size,
            })
          }
          arr.push(uploadImage(res.tempFilePaths[i]))
        }
      }
      let retArr: UploadRet[] = await Promise.allSettled(arr)
      setImgList(preImgList => {
        for (let i = 0; i < retArr.length; i++) {
          if (retArr[i].status === 'fulfilled') {
             preImgList.push(retArr[i]?.value?.data?.path as string)
          } else if (retArr[i].status === 'rejected'){
            preImgList.push('')
          }
        }
        hideLoading()
        return preImgList.slice()
      })
    } catch (err) {
      await Taro.showToast({
        title: '取消选择',
        icon: 'none'
      })
    }
  }

  async function onclickImg () {
    await Taro.previewImage({
      urls: imgList
    })
  }


  return <View className='container'>
    <Nav color='#000' text='上传' />
    <View className='img_list'>
      {
        imgList.map(img => <View className='img_list_item' key={img} onClick={onclickImg}>
          <Image className='img_list_item_url' src={img} />
        </View>)
      }
      <Label className='update iconfont' onClick={selectImage}>&#xe767;</Label>
    </View>
    <View className='upload_input'>
      <Input className='upload_title' placeholder='填写标题会有更多赞哦~'
        cursorSpacing={10}
        value={title}
        onInput={onchangeTitle}
      />
    </View>
    <View className='upload_text'>
      <Textarea className='upload_textarea'
        maxlength={500}
        autoHeight
        cursorSpacing={10}
        placeholder='添加正文'
        value={content}
        onInput={onchangeContent}
      />
    </View>
    <View className='label_wrap'>
      <View className='label_item'># 话题</View>
    </View>
    <Picker mode='region' value={area} customItem='全部' onChange={onChangeArea}>
      <View className='position_wrap'>
        <View className='iconfont'>&#xe64c; <Text style={{fontSize: '13px'}}>{
          area.length ? area.join('/') : '添加地点'
        }</Text></View>
        <View className='position_wrap_title'>标记位置让更多人看到</View>
        <Text className='iconfont'>&#xe88e;</Text>
      </View>
    </Picker>
    <View className='footer_wrap'>
      <View className='draft_wrap' onClick={cacheData}>
        <Text className='iconfont'>&#xe649;</Text>
        <Text className='draft_wrap_text'>存草稿</Text>
      </View>
      <Button className='draft_btn' onClick={onSend}>发布笔记</Button>
    </View>
    <Loading showLoading={show} color='#fff' show={show} />
  </View>
}

export default Upload
